import type { Menu } from '@/components/layout/SubMenu/interface'

export const useMenuStore = defineStore('menu', () => {
  // 由于map不支持持久化存储，单独存储菜单拍平数据
  const menuMap = ref(new Map<string, Menu.MenuOptions>())
  const btnMap = ref(new Map<string, string[]>())

  const setMenuMap = async (val: Menu.MenuOptions[]) => {
    menuMap.value.clear()
    btnMap.value.clear()
    val = JSON.parse(JSON.stringify(val))
    val.forEach((item) => {
      addToMap(item)
    })
  }
  const addToMap = (item: Menu.MenuOptions) => {
    if (item.type === 2) {
      // 按钮
      const _arr = item.path.split(':')
      const _item = btnMap.value.get(_arr[0])
      if (_item) {
        _item.push(_arr[1])
      } else {
        btnMap.value.set(_arr[0], [_arr[1]])
      }
    } else {
      // 菜单
      menuMap.value.set(item.path, item)
    }
    if (item.children) {
      item.children.forEach((child) => addToMap(child))
    }
  }

  return {
    menuMap,
    btnMap,
    setMenuMap
  }
})
